#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "nvs_storage.h"
#include <esp_log.h>

#define STORAGE_NAMESPACE "storage"

static const char *TAG = "storage";

esp_err_t save_wifi_data(wifi_data_t data)
{
    nvs_handle_t my_handle;
    esp_err_t err;

    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) return err;

    err = nvs_set_blob(my_handle, "wifi_data", &data, sizeof(wifi_data_t));

    if (err != ESP_OK) return err;
    ESP_LOGI(TAG,"Write Wifi ssid is [%s] passwd is [%s]\n",data.ssid,data.password);
    // Commit
    err = nvs_commit(my_handle);
    if (err != ESP_OK) return err;

    // Close
    nvs_close(my_handle);
    return ESP_OK;
}

esp_err_t read_wifi_data(wifi_data_t *data)
{
    nvs_handle_t my_handle;
    esp_err_t err;

    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) return err;
    size_t size = sizeof(wifi_data_t);
    err = nvs_get_blob(my_handle, "wifi_data", data, &size);
    if (err != ESP_OK) {
        return err;
    }
    ESP_LOGI(TAG,"Read Wifi ssid is [%s] passwd is [%s]\n",data->ssid,data->password);
    // Close
    nvs_close(my_handle);
    return ESP_OK;
}

esp_err_t save_color_data(led_color_t data)
{
    nvs_handle_t my_handle;
    esp_err_t err;

    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) return err;

    err = nvs_set_blob(my_handle, "color_data", &data, sizeof(led_color_t));

    if (err != ESP_OK) return err;
    ESP_LOGI(TAG,"Write color is %x %x %x \n",data.r,data.g,data.b);
    // Commit
    err = nvs_commit(my_handle);
    if (err != ESP_OK) return err;

    // Close
    nvs_close(my_handle);
    return ESP_OK;
}

esp_err_t read_color_data(led_color_t *data)
{
    nvs_handle_t my_handle;
    esp_err_t err;

    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
    if (err != ESP_OK) return err;
    size_t size = sizeof(led_color_t);
    err = nvs_get_blob(my_handle, "color_data", data, &size);
    if (err != ESP_OK) {
        return err;
    }
    ESP_LOGI(TAG,"Write color is %x %x %x \n",data->r,data->g,data->b);
    // Close
    nvs_close(my_handle);
    return ESP_OK;
}

void nvs_storage_init(void)
{
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK( err );

}